<template>
  <div class="earth-page" id="earthContainer">

  </div>
</template>

<script type="text/ecmascript-6">
import * as THREE from 'three'
// const OrbitControls = require('three-orbit-controls')
import {MTLLoader,OBJLoader} from 'three-obj-mtl-loader';
const OrbitControls = require('three-orbit-controls')(THREE);

export default {
  data() {
    return {
      scene:null,
      camera:null,
      renderer: null,
      mesh: null,
      control:null,
      container:null,
      group:null,

    }
  },
  components: {

  },
  mounted () {
    setTimeout(()=>{
      this.init();
      // this.render();
      this.animate();
    },0)

    // this.initWebSocket();
    // this.animate();
    // window.addEventListener( 'click', this.onMouseClick, false )
  },
  destroyed () {
    window.removeEventListener('resize',this.onWindowResize);
  },
  methods: {
    init(){
      var _this=this;
      this.container = document.getElementById('earthContainer');
      //创建渲染器
      this.renderer = new THREE.WebGLRenderer({
        alpha: true,
        antialias: true,
        preserveDrawingBuffer: true
      })
      this.group = new THREE.Group();
      this.earthGroup=new THREE.Group();
      //设置像素比
      this.renderer.setPixelRatio( window.devicePixelRatio );
      //设置渲染器的宽高
      this.renderer.setSize(this.container.clientWidth, this.container.clientHeight);
      //添加到容器中
      this.container.appendChild(this.renderer.domElement);
      //创建cameara
      this.camera = new THREE.PerspectiveCamera(45, this.container.clientWidth/this.container.clientHeight, 1, 3000);
      //创建camera位置
      this.camera.position.set(0, 600, 1500)
      this.camera.lookAt( 0, 0, 0 )

      //创建场景
      this.scene = new THREE.Scene();
      // this.scene.add( new THREE.GridHelper( 3000, 15 ) );
      this.group = new THREE.Group();
      this.scene.add(this.group);
      //创建光源
      var light = new THREE.DirectionalLight( 0x0c0c0c, 2 );
      light.position.set( 0, 300, 0 );
      this.scene.add(light);
      var ambiColor = "#b3b3b2";
      var ambientLight = new THREE.AmbientLight(ambiColor);
      this.scene.add(ambientLight);

      //创建轨道控制器 传入camera
      this.orbit = new OrbitControls( this.camera, this.renderer.domElement );
      this.orbit.update();

      this.loadMtlAndObj({
        MtlUrl:'static/models/sr5.mtl',
        ObjUrl:'static/models/sr5.obj',
        x:0,
        y:0,
        z:0,
        scale:60
      });

      window.addEventListener( 'resize', this.onWindowResize, false );
    },
    onWindowResize() {
				this.camera.aspect = window.innerWidth / window.innerHeight;
				this.camera.updateProjectionMatrix();
				this.renderer.setSize( window.innerWidth, window.innerHeight );
				this.render();
    },
    //封装MTL OBJ模型加载方法
    /**
     * @param params 对象类型
     * @param params.MtlUrl Mtl文件路径
     * @param params.ObjUrl Obj文件路径
     * @param params.scale 缩放比
     * @param params.x y z  位置
     * @param params.rotate arr['x|y|z',val]  旋转
     * @return:
     */
    loadMtlAndObj(params){
      var _this=this;
      var mtlLoader = new MTLLoader();
      mtlLoader.load(
        params.MtlUrl,
        function(materials){
          var objLoader = new OBJLoader();
          objLoader.setMaterials(materials);
          objLoader.load(params.ObjUrl,
            function (object) {
              object.traverse( function ( child ) {
                  child.castShadow = false;// 是否启用阴影选项
                  if ( child instanceof THREE.Mesh ) {
                      //child.material.map = texture;
                  }
              } );
              // object.getName('name');
              object.position.x = params.x||0;
              object.position.y = params.y||0;
              object.position.z = params.z||0;

              object.scale.x = params.scale||1;
              object.scale.y = params.scale||1;
              object.scale.z = params.scale||1;
              if(params.zhou){
                switch(params.zhou[0]){
                  case 'x':
                    object.rotateX(params.zhou[1]);
                    break;
                  case 'y':
                    console.log('params.zhou[0]>>',params.zhou[0])
                    object.rotateY(params.zhou[1]);
                    break;
                  case 'z':
                    object.rotateZ(params.zhou[1]);
                    break;
                }
              }
              object.rotation.y = THREE.Math.degToRad( 180 );
              // console.log('object.children>>>',object.children)
              //关键  重置导入模型在three.js坐标系的原点
              object.children[0].geometry.computeBoundingBox();
              object.children[0].geometry.center()
              _this.group.add(object);

            }
          )
        }
      )
    },
    //渲染
    render() {
      this.renderer.render(this.scene, this.camera); // 结合场景和相机进行渲染，即用摄像机拍下此刻的场景
      requestAnimationFrame(this.render); // 让浏览器执行参数中的函数，不断循环（浏览器一个新的API）
    },
    //设置3d动态效果 并渲染
    animate(bool) {
      // var _this=this;
      // if(bool){
        this.group.rotation.y -= 0.004;
      // }else{
      //   _this.group.rotation.y =0;
      // }

        requestAnimationFrame(this.animate);
        this.renderer.render(this.scene, this.camera);
    }
  }
}
</script>

<style scoped lang='scss'>
.earth-page{
  width: 100%;
  height: 100%;
  background: transparent;
  overflow: hidden;
}
</style>
